package main

import (
	//"crypto/tls"
	"main/gmsm/x509"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"main/gmsm/gmtls"
)

func main() {
	// 加载 SM2 签名证书和私钥
	sigCert, err := gmtls.LoadX509KeyPair("../subCert.crt", "../subCert.key")
	if err != nil {
		log.Fatalf("Failed to load SM2 signature certificate: %v", err)
	}

	// 加载 SM2 加密证书和私钥（如果需要）
	encCert, err := gmtls.LoadX509KeyPair("../caSM2.crt", "../caSM2.key")
	if err != nil {
		log.Fatalf("Failed to load SM2 encryption certificate: %v", err)
	}

	// 加载根证书池（用于客户端验证）
	rootCAs := x509.NewCertPool()
	caCert, err := ioutil.ReadFile("../caSM2.crt")
	if err != nil {
		log.Fatalf("Failed to read CA certificate: %v", err)
	}
	if !rootCAs.AppendCertsFromPEM(caCert) {
		log.Fatalf("Failed to parse CA certificate")
	}

	// 配置 GMTLS
	gmtlsConfig := &gmtls.Config{
		GMSupport:    gmtls.NewGMSupport(),
		Certificates: []gmtls.Certificate{sigCert, encCert},
		RootCAs:      rootCAs,
	}

	ln, err := gmtls.Listen("tcp", ":443", gmtlsConfig)
	if err != nil {
		log.Println(err)
		return
	}
	defer ln.Close()

	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		fmt.Fprintf(writer, "hello\n")
	})
	fmt.Println(">> HTTP Over [GMSSL/TLS] running...")
	err = http.Serve(ln, nil)
	if err != nil {
		panic(err)
	}
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, this is a GM/TLS server!")
}